import {defineStore} from "pinia"
import type{loginFormInfoType} from '@/views/user/login/type'
import router from "@/router"
import {userApi} from "@/mock"
import {auth as useAuth,navTags as useNavTags} from "@/store"
import {authRouteMode} from "@/common/config"
import {resetRouter} from "@/router"


export default defineStore('user',{
    state:()=>({
      info:{} as userType,            // 用户信息
      loginInfo:{} as loginFormInfoType,   // 登录表单信息
    }),
    actions:{
      setUser(user:userType){
         this.info=user
      },
      async loginByAccount(user:{userName:string,password:string}){
        let res  
        res=await userApi.getUserInfoByAccount(user)
          console.log(res)
          if(res.code==200)
          { 
            this.setUser(res.info)
            return {code:200,...res.info}
          }
          else if(res.code=201){
            return {code:201}
          } 
          return false
      },
      async loginByPhone(user:{phone:string,verifyCode:string}){
        let res  
        res=await userApi.getUserInfoByPhone(user)
          console.log(res)
          if(res.code==200)
          { 
            this.setUser(res.info)
            return {code:200,...res.info}
          }
          else if(res.code=201){
            return {code:201}
          } 
          return false
      },
      // async函数里的同步任务执行完毕后就会调用它的rel
      async logout(redirect:string){
          await new Promise(rel=>{
             setTimeout(()=>{rel({})},1000)
          })
          this.info={} as userType
          const auth=useAuth()
          const navTags=useNavTags()
          router.replace({path:"/login",query:{redirect:encodeURIComponent(redirect)}})
          navTags.clearTags(true)
          if(authRouteMode!=="local") 
          {
            auth.clearRoutes()
            resetRouter()
          }
      }
    },
    

})